package com.shujia.scala

import java.util
import scala.io.Source

object Demo13WordCount {
  def main(args: Array[String]): Unit = {
    //1、读取文件
    val lines: List[String] = Source.fromFile("data/lines.txt").getLines().toList

    //1、使用循环实现
    //创建空的字典
    val wordCount = new util.HashMap[String, Integer]()
    for (line <- lines) {
      //安装逗号切分
      val split: Array[String] = line.split(",")
      for (word <- split) {
        //如果字典中存在就加1,如果不存在就存入一个1
        if (wordCount.containsKey(word)) {
          wordCount.put(word, wordCount.get(word) + 1)
        } else {
          wordCount.put(word, 1)
        }
      }
    }
    println(wordCount)


    //flatMap传入一行返回多行，相当于explode
    val words: List[String] = lines
      //一行转换多行
      .flatMap((line: String) => line.split(","))

    //按照单词进行分组
    val groupByList: Map[String, List[String]] = words
      .groupBy((word: String) => word)

    //统计单词的数量
    val wc: Map[String, Int] = groupByList
      .mapValues(value => value.length)

    wc.foreach(println)

    //链式调用
    lines
      .flatMap(_.split(","))
      .groupBy(w=>w)
      .mapValues(_.length)
      .foreach(println)
  }
}
